package com.example.awayreply;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class MainActivity extends Activity
{
	public static final char DELIM_CHAR = '|';
	
	private EditText myReplyMessageField;
	private CheckBox myEnableCheckBox;
	
	private String myMessageText;
	private String myFileName;
	private File myFileLocation;
	private File myFile;
	
	private FileOutputStream myFileOutStream;
	private InputStream myInputStream;
    private InputStreamReader myInStreamReader;
    private BufferedReader myBufferedReader;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{	
		String temp = null;
		String buffer = null;
		int chopIndex = -1;
		
		try
		{
			super.onCreate(savedInstanceState);

			setContentView(R.layout.activity_main);

			// Initialize variables here ==================================================
			myMessageText = "";
			myFileName = "awayreply.txt";
			myFileLocation = this.getFilesDir();
			
			myReplyMessageField = (EditText)findViewById(R.id.replyMessageField);
			myEnableCheckBox = (CheckBox)findViewById(R.id.enableCheckBox);
			
			myFile = new File(myFileLocation, myFileName);
			
			if(myFile.exists() == false)
			{
				myFile.createNewFile();
			}
			else
			{
				myInputStream = openFileInput(myFileName);
				myInStreamReader = new InputStreamReader(myInputStream);
				myBufferedReader = new BufferedReader(myInStreamReader);
				//==============================================================================
				
				if(myInputStream != null && myInStreamReader != null)
				{
					while((temp = myBufferedReader.readLine()) != null)
					{
	                    buffer += temp;
	                }
				}

				
				myInputStream.close();
				
				if(buffer != null)
				{
					chopIndex = buffer.indexOf(DELIM_CHAR);
					
					if(chopIndex >= 0)
					{
						//Take up to only the first part of the file
						myMessageText = buffer.substring(0, chopIndex);
						
						myReplyMessageField.setText(myMessageText);
						
						myReplyMessageField.setOnEditorActionListener(myListener);
						
						//Take the second half of the file representing if the check box 
						//was enabled or not upon closing.
						temp = buffer.substring(chopIndex  + 1);

						if(temp.equals("true"))
						{
							myEnableCheckBox.setChecked(true);
						}
						else
						{
							myEnableCheckBox.setChecked(false);
						}
					}
				}
			}//End else	
		} 
		catch (Exception ex) 
		{
			Log.e("fread", ex.getMessage());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		
		return true;
	}
	
	@Override
	public void onStop()
	{
		super.onStop();
	}
	
	//Listeners
	
	//Respond when the enabled box is checked, set up service if not already enabled. If its
	//enabled then remove the old service and replace, then write the change to the file.
	
	//Respond when the enabled box is unchecked, remove the service and write the change
	//to the file.
	
	//Respond when the done button is clicked.
	protected OnEditorActionListener myListener = new OnEditorActionListener() 
	{
	    @Override
	    public boolean onEditorAction(TextView txtView, int actionId, KeyEvent event) 
	    {
			boolean handled = false;
			String secondPart = "" + myEnableCheckBox.isChecked();

			try 
			{
				if (actionId == EditorInfo.IME_ACTION_DONE)
				{
					
					myFileOutStream = openFileOutput(myFileLocation.getAbsolutePath() + myFileName, Context.MODE_PRIVATE);
					
					myMessageText = txtView.getText().toString();

					myFileOutStream.write(myMessageText.getBytes());
					myFileOutStream.write(DELIM_CHAR);
					myFileOutStream.write(secondPart.getBytes());
					myFileOutStream.close();

					handled = true;
				}

			} 
			catch (Exception e)
			{
				Log.e("fwrite", e.getMessage());
			}

	        return handled;
	    }
	};
}
